<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reservationApi, roomApi, userApi, timeUtils } from '../api/index'
import { useRouter } from 'vue-router'

const router = useRouter()
const reservations = ref([])
const rooms = ref([])
const loading = ref(false)
const currentUser = ref(JSON.parse(localStorage.getItem('user')) || null)

// 过滤条件
const filters = ref({
  status: '',
  roomId: ''
})

onMounted(async () => {
  if (!currentUser.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  await Promise.all([
    fetchMyReservations(),
    fetchRooms()
  ])
})

const fetchMyReservations = async () => {
  loading.value = true
  try {
    const res = await reservationApi.getUserReservations(currentUser.value.id)
    reservations.value = res.data
  } catch (error) {
    console.error('获取我的预约列表失败:', error)
    ElMessage.error('获取我的预约列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchRooms = async () => {
  try {
    const res = await roomApi.getAllRooms()
    rooms.value = res.data
  } catch (error) {
    console.error('获取会议室列表失败:', error)
  }
}

const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消该预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await reservationApi.cancelReservation(row.id)
      ElMessage.success('预约已取消')
      await fetchMyReservations()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }).catch(() => {})
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return timeUtils.formatLocal(dateTimeStr);
}

const getRoomName = (roomId) => {
  const room = rooms.value.find(r => r.id === roomId)
  return room ? room.name : '未知会议室'
}

const getStatusTag = (status) => {
  switch (status) {
    case 'PENDING':
      return { type: 'warning', label: '待审批' }
    case 'APPROVED':
      return { type: 'success', label: '已批准' }
    case 'REJECTED':
      return { type: 'danger', label: '已拒绝' }
    case 'CANCELLED':
      return { type: 'info', label: '已取消' }
    default:
      return { type: '', label: status }
  }
}

const handleFilter = async () => {
  loading.value = true
  try {
    const res = await reservationApi.getUserReservations(currentUser.value.id)
    let filtered = res.data
    
    if (filters.value.status) {
      filtered = filtered.filter(item => item.status === filters.value.status)
    }
    
    if (filters.value.roomId) {
      filtered = filtered.filter(item => item.room && item.room.id === filters.value.roomId)
    }
    
    reservations.value = filtered
  } catch (error) {
    console.error('筛选预约失败:', error)
    ElMessage.error('筛选预约失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const resetFilter = async () => {
  filters.value = {
    status: '',
    roomId: ''
  }
  await fetchMyReservations()
}

const handleNewReservation = () => {
  router.push('/new-reservation')
}

// 计算过滤后的预约列表
const filteredReservations = computed(() => {
  return reservations.value.map(res => {
    return {
      ...res,
      roomName: getRoomName(res.room?.id),
      formattedStartTime: formatDateTime(res.startTime),
      formattedEndTime: formatDateTime(res.endTime),
      statusTag: getStatusTag(res.status)
    }
  })
})
</script>

<template>
  <div class="my-reservations-container">
    <div class="page-header">
      <h2>我的预约</h2>
      <el-button type="primary" @click="handleNewReservation">新建预约</el-button>
    </div>
    
    <el-card shadow="hover" class="filter-card">
      <div class="filter-container">
        <el-select v-model="filters.status" placeholder="按状态筛选" clearable class="filter-item">
          <el-option label="待审批" value="PENDING" />
          <el-option label="已批准" value="APPROVED" />
          <el-option label="已拒绝" value="REJECTED" />
          <el-option label="已取消" value="CANCELLED" />
        </el-select>
        
        <el-select v-model="filters.roomId" placeholder="按会议室筛选" clearable class="filter-item">
          <el-option 
            v-for="room in rooms" 
            :key="room.id" 
            :label="room.name" 
            :value="room.id" 
          />
        </el-select>
        
        <div class="filter-buttons">
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <el-empty v-if="filteredReservations.length === 0" description="暂无预约记录" />
      
      <el-table
        v-else
        v-loading="loading"
        :data="filteredReservations"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="roomName" label="会议室" width="120" />
        <el-table-column prop="formattedStartTime" label="开始时间" width="150" />
        <el-table-column prop="formattedEndTime" label="结束时间" width="150" />
        <el-table-column prop="purpose" label="用途" min-width="120" />
        <el-table-column prop="attendees" label="参会人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.statusTag.type">
              {{ scope.row.statusTag.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                v-if="['PENDING', 'APPROVED'].includes(scope.row.status)"
                size="small"
                type="warning"
                @click="handleCancel(scope.row)"
              >
                取消
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.my-reservations-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.filter-item {
  width: 180px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: flex-start;
}

.action-buttons .el-button {
  margin-left: 0;
  margin-right: 0;
}

@media (max-width: 768px) {
  .filter-item {
    width: 100%;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style> 